package com.cl.short_video_java.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cl.short_video_java.annotation.IsRole;
import com.cl.short_video_java.annotation.Login;
import com.cl.short_video_java.common.Const;
import com.cl.short_video_java.exception.WebException;
import com.cl.short_video_java.pojo.SysRoleMenu;
import com.cl.short_video_java.pojo.VideoUser;
import com.cl.short_video_java.service.SysRoleMenuService;
import com.cl.short_video_java.service.VideoUserService;
import com.cl.short_video_java.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 付
 * @Date 2024-11-17 10:34
 * @Version 1.0
 * @description 角色判断切面
 * @since 1.0
 */

@Slf4j
@Component
public class IsRoleAspect implements HandlerInterceptor {
	@Resource
	JwtUtil jwtUtil;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private VideoUserService videoUserService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("权限判断==================");
		IsRole annotation;
		// 判断当前请求是否为方法，如果是，就对其进行注解判断
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(IsRole.class);
		} else {
			return true;
		}
		if (annotation == null) {
			return true;
		}
		String token = request.getHeader("token");
		int menuId = annotation.menuId();
		// 判断token是否合法
		if (!StringUtils.hasText(token)) {
			throw new WebException("请先登录", 401);
		}
		// 判断token内容是否存在，且是否超时

		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);

		if (claim == null || jwtUtil.isTokenExpired(claim.getExpiration())) {
			throw new WebException("请先登录", 401);
		}
		VideoUser user = videoUserService.getCurrentUser(request, Const.GRADE_ADMIN);
		if (user.getId() == null) {
			throw new WebException("请先登录", 401);
		}

		Integer userRoleId = user.getRoleId();
		if (userRoleId == 1) {
			//超管
			return true;
		}

		long count = sysRoleMenuService.count(new QueryWrapper<SysRoleMenu>().eq("role_id", userRoleId).eq("menu_id", menuId).eq("status",1));
		log.info("权限是否足够呢", count);
		if (count == 0) {
			throw new WebException("权限不足");
		}
		return true;
	}
}
